from lsocket import LSocket, LSocketMaintenance
from time import time
from threading import Thread

class ReceiveThread(Thread):
    def __init__(self, conn):
        super(ReceiveThread, self).__init__()
        self._conn = conn
    
    def run(self):
        try:
            length = int(self._conn.recv(1024))
            print 'got length', length
            self._conn.send('ACK')
            recvd_so_far = 0
            start = time()
            while recvd_so_far < length:
                print 'receiving data', 
                data = self._conn.recv(length - recvd_so_far)
                print len(data)
                recvd_so_far += len(data)
            stop = time()
            print 'data received in', stop-start, 'seconds at rate', length/(stop-start)/1024.0, 'kb/s'
            self._conn.send('ACK')
        finally:
            self._conn.close()
        
LSocket.set_upload_limit(256)
sock = LSocket()
conn = None
try:
    sock.bind(('', 23456))
    sock.listen(2)
    
    print 'waiting for connection'
    threads = []
    for x in range(0, 2):        
        conn, addr = sock.accept()
        print 'got connection from', addr
        thread = ReceiveThread(conn)
        thread.start()
        threads.append(thread)
    
    for thread in threads:
        thread.join()
    
finally:
    LSocketMaintenance.shutdown()
    if conn: conn.close()
    sock.close()

